package com.ruoyi.common.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SendCodeUtils {
    public static Client createClient() throws Exception {
        Config config = new Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId("LTAI5t9Qnx1TzUDQvFQ8yW7D")
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret("WQEc7ihbFd3uW2XiTFshL2WvJwbb7M");
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    public static String message(String phoneNumber) {
        // 请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例使用环境变量获取 AccessKey 的方式进行调用，仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html
        com.aliyun.dysmsapi20170525.Client client = null;
        try {
            client = SendCodeUtils.createClient();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
        RandomUtils randomUtils = new RandomUtils();
        String confirmCode = randomUtils.getCodeRandom();
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setPhoneNumbers(phoneNumber)
                .setSignName("YY阅读")
                .setTemplateCode("SMS_463638550")
                .setTemplateParam("{\"code\":\"" + confirmCode + "\"}");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            if ("OK".equals(sendSmsResponse.getBody().getCode())) {
                return confirmCode;
            } else {
                log.error("发送验证码失败:code{},messgae:{}", sendSmsResponse.getBody().getCode(),
                        sendSmsResponse.getBody().getMessage());
                return null;
            }
        } catch (Exception error) {
            log.error("发送验证码失败:{}", error.getMessage(), error);
            return null;
        }
    }
}
